import 'package:get/get.dart';
import '../providers/device_provider.dart';
import '../models/device_model.dart';
import 'package:dio/dio.dart';
import 'dart:convert';

class DeviceRepository {
  final DeviceProvider _deviceProvider = Get.find<DeviceProvider>();
  
  /// 获取设备列表
  Future<DeviceListResponse> getDeviceList({
    int pageNum = 1,
    int pageSize = 10,
    String? deviceName,
    String? deviceSn,
    String? productKey,
    int? status,
    String? beginTime,
    String? endTime,
  }) async {
    return await _deviceProvider.getDeviceList(
      pageNum: pageNum,
      pageSize: pageSize,
      deviceName: deviceName,
      deviceSn: deviceSn,
      productKey: productKey,
      status: status,
      beginTime: beginTime,
      endTime: endTime,
    );
  }
  
  /// 获取设备详情
  Future<DeviceDetailResponse> getDeviceDetail(int deviceId) async {
    return await _deviceProvider.getDeviceDetail(deviceId);
  }
  
  /// 通过设备序列号查询设备
  Future<DeviceDetailResponse> getDeviceBySn(String deviceSn) async {
    return await _deviceProvider.getDeviceBySn(deviceSn);
  }
  
  /// 获取设备统计信息
  Future<DeviceStatsResponse> getDeviceStats() async {
    return await _deviceProvider.getDeviceStats();
  }
  
  /// 根据产品ID查询设备列表
  Future<DeviceListResponse> getDevicesByProductId(
    int productId, {
    int pageNum = 1,
    int pageSize = 10,
  }) async {
    return await _deviceProvider.getDevicesByProductId(
      productId,
      pageNum: pageNum,
      pageSize: pageSize,
    );
  }
  
  /// 获取设备最新状态
  Future<DeviceDetailResponse> getDeviceLatestStatus(String deviceSn) async {
    return await _deviceProvider.getDeviceLatestStatus(deviceSn);
  }
  
  /// 新增设备
  Future<void> addDevice({
    required String deviceName,
    required String deviceSn,
    required int productId,
    required int nodeType,
    String? location,
    double? longitude,
    double? latitude,
    String? tags,
  }) async {
    await _deviceProvider.addDevice(
      deviceName: deviceName,
      deviceSn: deviceSn,
      productId: productId,
      nodeType: nodeType,
      location: location,
      longitude: longitude,
      latitude: latitude,
      tags: tags,
    );
  }
  
  /// 修改设备
  Future<void> updateDevice({
    required int deviceId,
    String? deviceName,
    String? location,
    double? longitude,
    double? latitude,
    String? tags,
  }) async {
    await _deviceProvider.updateDevice(
      deviceId: deviceId,
      deviceName: deviceName,
      location: location,
      longitude: longitude,
      latitude: latitude,
      tags: tags,
    );
  }
  
  /// 删除设备
  Future<void> deleteDevices(List<int> deviceIds) async {
    await _deviceProvider.deleteDevices(deviceIds);
  }
  
  /// 获取主页所需统计数据
  Future<Map<String, int>> getHomeStatistics() async {
    return await _deviceProvider.getHomeStatistics();
  }
  
  /// 获取设备属性历史数据
  /// 
  /// [deviceSn] 设备序列号
  /// [startTime] 开始时间戳(毫秒)，可选
  /// [endTime] 结束时间戳(毫秒)，可选
  /// [properties] 要查询的属性列表，多个用逗号分隔，可选
  /// [pageSize] 每页记录数，默认100
  /// [pageNum] 页码，从1开始，默认1
  Future<dynamic> getDevicePropertiesHistory({
    required String deviceSn,
    int? pageSize,
    int? pageNum,
    String? startTime,
    String? endTime,
  }) async {
    try {
      final queryParams = <String, dynamic>{
        'deviceSn': deviceSn,
        'pageSize': pageSize ?? 100,
        'pageNum': pageNum ?? 1,
      };

      if (startTime != null) queryParams['startTime'] = startTime;
      if (endTime != null) queryParams['endTime'] = endTime;

      print('设备属性历史查询参数: $queryParams');

      // 转换时间戳字符串为整数（如果存在）
      int? startTimeInt;
      int? endTimeInt;
      
      if (startTime != null) {
        startTimeInt = int.tryParse(startTime);
        print('转换startTime: $startTime -> $startTimeInt');
      }
      
      if (endTime != null) {
        endTimeInt = int.tryParse(endTime);
        print('转换endTime: $endTime -> $endTimeInt');
      }

      final result = await _deviceProvider.getDevicePropertiesHistory(
        deviceSn: deviceSn,
        startTime: startTimeInt,
        endTime: endTimeInt,
        pageSize: pageSize ?? 100,
        pageNum: pageNum ?? 1,
      );

      print('API请求成功');
      
      // 记录响应数据的一部分，避免日志过长
      final resultPreview = result.toString();
      final truncatedPreview = resultPreview.length > 500 
          ? '${resultPreview.substring(0, 500)}...(截断)' 
          : resultPreview;
      print('原始响应数据: $truncatedPreview');
      
      // 检查响应数据的类型
      print('响应数据类型: ${result.runtimeType}');
      
      return result;
    } catch (e) {
      print('设备属性历史查询异常: $e');
      
      // 检查是否为DioException，并尝试提取更多详细信息
      if (e is DioException) {
        final dioError = e;
        print('Dio错误类型: ${dioError.type}');
        print('Dio错误消息: ${dioError.message}');
        
        // 如果响应不为空，记录响应信息
        if (dioError.response != null) {
          final statusCode = dioError.response?.statusCode;
          print('响应状态码: $statusCode');
          
          // 特别处理状态码为200的情况
          if (statusCode == 200) {
            print('状态码为200但仍有Dio错误，尝试手动处理响应数据');
            final responseData = dioError.response?.data;
            
            if (responseData != null) {
              print('响应数据类型: ${responseData.runtimeType}');
              
              // 尝试解析响应数据
              try {
                if (responseData is Map<String, dynamic>) {
                  print('响应数据是有效的Map，直接返回');
                  return responseData;
                } else if (responseData is String) {
                  print('响应数据是字符串，尝试解析为JSON');
                  try {
                    final parsedData = _parseJsonResponse(responseData);
                    print('字符串解析为JSON成功');
                    return parsedData;
                  } catch (parseError) {
                    print('字符串解析为JSON失败: $parseError');
                  }
                }
                
                // 如果不能解析为JSON但状态码是200，返回原始数据
                print('无法解析为标准格式，但状态码为200，返回原始数据');
                return {'raw': responseData};
              } catch (parseError) {
                print('手动处理响应数据失败: $parseError');
              }
            }
          } else {
            // 非200状态码，记录响应数据
            print('非200状态码，响应数据: ${dioError.response?.data}');
          }
        } else {
          print('Dio错误没有响应对象');
        }
      }
      
      // 重新抛出异常
      rethrow;
    }
  }
  
  /// 尝试将字符串解析为JSON对象
  Map<String, dynamic> _parseJsonResponse(String jsonString) {
    try {
      // 移除可能导致解析失败的BOM或其他前缀字符
      String cleanedJson = jsonString;
      if (jsonString.startsWith('\uFEFF')) {
        cleanedJson = jsonString.substring(1);
      }
      
      // 解析JSON
      final parsed = jsonDecode(cleanedJson) as Map<String, dynamic>;
      return parsed;
    } catch (e) {
      print('JSON解析错误: $e');
      throw Exception('JSON解析失败: $e');
    }
  }
} 